<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Validate;
use think\Session;
use app\index\model\Account;
use app\index\model\Group;
use app\index\model\User;

class Index extends Controller
{
    /**
     * 返回二维码和微信号
     */
    public function index()
    {
        $groupIds = Group::getSelected();
        $account  = Account::getAccount($groupIds);

        return view('index', compact('account'));
    }

    /**
     * 管理页
     */
    public function admin()
    {
        if (! Session::has('user')) {
            $this->error('请先登录', 'index/login');
        }

        $groups = Group::all();
        $accounts = Account::all();

        return view('admin', compact('groups', 'accounts'));
    }

    public function login(Request $request)
    {
        if ($request::instance()->isGet()) {
            return view('login');
        } elseif ($request::instance()->isPost()) {
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require',
            ]);
            $data = input('post.');
            if (! $validate->check($data)) {
                $this->error($validate->getError());
                return ;
            }

            $result = User::checkLogin($data);
            if ($result['result'] === true) {
                Session::set('user', $result['user']);
                $this->success('登录成功', 'index/admin');
            } else {
                $this->error('用户名或密码不正确');
            }
        }
    }

    public function logout()
    {
        Session::clear();
        $this->success('注销成功', 'index/');
    }
}
